//
//  ReaderViewController.m
//  Jula_iOS
//
//  Created by adiljan on 16/3/19.
//  Copyright © 2016年 Alimjan. All rights reserved.
//

#import "ReaderViewController.h"


#import <QuartzCore/QuartzCore.h>
#import "UIWebView+SearchWebView.h"
#import "EPubBookLoader.h"
#import "MessageHelper.h"
#import "Constants.h"
#import "DXAlertView.h"
#import "ReaderLightView.h"
#import "ASValueTrackingSlider.h"
#import "AlertWaiting.h"
//#import "GADBannerView.h"
//#import "DownloadedItem.h"
#define PHONE_WIDTH [UIScreen mainScreen].bounds.size.width
#define PHONE_HEIGHT [UIScreen mainScreen].bounds.size.height
#define StringForKey(key) [NSString stringWithFormat:@"%@",key]
#define READER_LIST_TOP_BUTTON 38
#define BACK_HEIGHT 50
#define READER_LIST_RIGHT 30
#define TOOL_BAR_HEIGHT READER_LIST_TOP_BUTTON+BACK_HEIGHT
//判断是否为iPhone6plus
#define IPHONE6PLUS [[UIScreen mainScreen] bounds].size.height >= 736.0f

@interface ReaderViewController()

- (void) gotoNextSpine;
- (void) gotoPrevSpine;
- (void) gotoNextPage;
- (void) gotoPrevPage;
- (int)  getGlobalPageCount;
- (void) gotoPageInCurrentSpine: (int)pageIndex;
- (void) updatePagination;
- (void) toLastReadPage;
- (void) recordLastReadPage;


@end

@implementation ReaderViewController
@synthesize strUpubPath;
@synthesize bookLoader;
@synthesize loadedEpub;
@synthesize toolbar;
@synthesize tblReaderList;
@synthesize backbar;
@synthesize pageView;
@synthesize lightView;
@synthesize webView;
@synthesize btnReadMode;
@synthesize btnLight;
@synthesize btnSmallFont;
@synthesize btnBigFont;
@synthesize btnShowPage;
//@synthesize pageSlider;
@synthesize currentPageLabel;
@synthesize currentPageLabel2;
@synthesize epubLoaded;
@synthesize paginating;
@synthesize enablePaging;
@synthesize searching;
@synthesize currentSpineIndex;
@synthesize currentPageInSpineIndex;
@synthesize pagesInCurrentSpineCount;
@synthesize currentTextSize;
@synthesize totalPagesCount;
@synthesize hud;
@synthesize isClearWebViewContent;
@synthesize window = _window;
-(id)init{
    self = [super init];
    if(self!=nil){
        self.enablePaging = NO;
        self.isClearWebViewContent = NO;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadBook:) name:@"loadBook" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadChapter:) name:@"loadChapter" object:nil];
    
    return self;
}

// 状态栏颜色
- (UIStatusBarStyle)preferredStatusBarStyle

{
    
    CGFloat  backHeight = IPHONE6PLUS?BACK_HEIGHT+12:BACK_HEIGHT;
    
    CGFloat backViewY = self.backbar.frame.origin.y;
    // 上面返回view显示时候状态栏颜色改为白色  不显示时改为黑色
    if ((int)backViewY != -backHeight ) {
        return UIStatusBarStyleLightContent;  // 白色
        
    }else{
        return UIStatusBarStyleDefault;  // 默认黑色
    }
}

// 是否显示状态栏
- (BOOL)prefersStatusBarHidden
{
    return NO; //返回NO表示要显示，返回YES将hiden
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [super viewDidLoad];
    
    NSString *epubPath = [[NSBundle mainBundle] pathForResource:@"hikaye" ofType:@"epub"];
    strUpubPath = epubPath;
    
    self.view.frame = [[UIScreen mainScreen] bounds];
    self.view.layer.cornerRadius = 3;
    self.view.clipsToBounds = YES;
    isNightMode=NO;
    isHiddenLightView = YES;
    isHiddenPageView = YES;
    isHiddenReaderList = YES;
    strBackGroundCSS=@"addCSSRule('body', 'background-color: transparent; color:black;')";
    
    
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(5, 50, self.view.frame.size.width-10, self.view.frame.size.height - 60)];
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"reader_back"]]];
    [webView setBackgroundColor:[UIColor clearColor]];
    webView.opaque = NO;
    [webView setDelegate:self];
    
    [self.view addSubview:webView];
    // 返回
    NSArray *nibBack = [[NSBundle mainBundle] loadNibNamed:@"ReaderBackView" owner:nil options:nil];
    self.backbar = [nibBack objectAtIndex:0];
    IconButton *btnBack = (IconButton *)[self.backbar viewWithTag:10005];
    [btnBack addTarget:self action:@selector(btnReturn_Click:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backbar];
    
    // 目录按钮
    btnList = (IconButton *)[self.backbar viewWithTag:10010];
    [btnList addTarget:self action:@selector(btnReaderList_Clicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backbar];
    
    
    singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleFingerEvent)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate = self;
    //    singleFingerOne.enabled = NO;
    [self.webView addGestureRecognizer:singleFingerOne];
    
    
    UIScrollView* sv = nil;
    for (UIView* v in  webView.subviews) {
        if([v isKindOfClass:[UIScrollView class]]){
            sv = (UIScrollView*) v;
            sv.scrollEnabled = NO;
            sv.bounces = NO;
        }
    }
    // 默认字体大小
    currentTextSize = 120;
    
    pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(onPangesture:)];
    
    [webView addGestureRecognizer:pan];
    
    // 顶部显示页数标签
    self.currentPageLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.webView.frame.size.width/2-25, 35, 50, 10)];
    
    currentPageLabel.backgroundColor = [UIColor clearColor];
    currentPageLabel.font = [UIFont systemFontOfSize:12];
    currentPageLabel.textAlignment = UITextAlignmentCenter;
    currentPageLabel.textColor = [UIColor colorWithRed:37/255.f green:37/255.f blue:37/255.f alpha:1];
    [self.view addSubview:currentPageLabel];
    
    //视图下方显示的工具栏
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ReadToolbarView" owner:nil options:nil];
        self.toolbar = [nib objectAtIndex:0];
        
        //初始化屏幕亮度设置按钮
        
        self.btnLight = (IconButton *)[self.toolbar viewWithTag:10000];
        [btnLight addTarget:self action:@selector(btnLight_Clicked:) forControlEvents:UIControlEventTouchUpInside];
        //初始化显示页码按钮
        
        NSArray *nibPage = [[NSBundle mainBundle] loadNibNamed:@"ReaderPageView" owner:nil options:nil];
        self.pageView = [nibPage objectAtIndex:0];
        
        [self.pageView.sliderPageView setMinimumValue:0];
        [self.pageView.sliderPageView setMaximumValue:100];
        [self.pageView.sliderPageView addTarget:self action:@selector(slidingEnded:) forControlEvents:UIControlEventTouchUpInside];
        [self.pageView.sliderPageView addTarget:self action:@selector(slidingEnded:) forControlEvents:UIControlEventTouchUpOutside];
        [self.pageView.sliderPageView addTarget:self action:@selector(slidingChanged:) forControlEvents:UIControlEventValueChanged];
        [self.pageView.sliderPageView addTarget:self action:@selector(slidingStarted:) forControlEvents:UIControlEventTouchDown];
        
        
        self.btnShowPage = (IconButton *)[self.toolbar viewWithTag:10001];
        [btnShowPage addTarget:self action:@selector(btnJumpPage_Clicked:) forControlEvents:UIControlEventTouchUpInside];
        //初始化字体缩小按钮
        self.btnSmallFont = (IconButton *)[self.toolbar viewWithTag:10002];
        [btnSmallFont addTarget:self action:@selector(btnSmallFont_Clicked:) forControlEvents:UIControlEventTouchUpInside];
        //初始化字体放大按钮
        self.btnBigFont = (IconButton *)[self.toolbar viewWithTag:10003];
        [btnBigFont addTarget:self action:@selector(btnBigFont_Clicked:) forControlEvents:UIControlEventTouchUpInside];
        //初始化设置阅读模式按钮
        self.btnReadMode = (IconButton *)[self.toolbar viewWithTag:10004];
        [btnReadMode addTarget:self action:@selector(btnReadMode_Clicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:self.toolbar];
        
    }
    //初始化显示当前页码的标签
    UILabel *_pageText = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width, (self.view.frame.size.height+80)/2, 100, 30)];
    _pageText.layer.cornerRadius = 5;
    _pageText.backgroundColor = [UIColor colorWithRed:68/255.f green:68/255.f blue:68/255.f alpha:1];
    _pageText.textColor = [UIColor colorWithRed:172/255.f green:134/255.f blue:98/255.f alpha:1];
    _pageText.font = [UIFont systemFontOfSize:24];
    _pageText.textAlignment = NSTextAlignmentCenter;
    self.currentPageLabel2 = _pageText;
    
    [self.view addSubview:currentPageLabel2];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bookDidLoaded:) name:@"bookDidLoaded" object:nil];
    [self loadBook];
    
    
}


- (void) loadChapter:(NSNotification *)notification{
    [self hideToolbar];
    
    NSString *chapter = (NSString *)[notification object];
    [self loadSpine:[chapter intValue] atPageIndex:0];
}

- (void) loadBook:(NSNotification *)notification{
    
    [currentPageLabel setText:@"0/0"];
    
    //NSString *path = [notification object];
    NSString* path=strUpubPath;
    currentSpineIndex = 0;
    currentPageInSpineIndex = 0;
    pagesInCurrentSpineCount = 0;
    totalPagesCount = 0;
    searching = NO;
    epubLoaded = NO;
    
    self.isClearWebViewContent = YES;
    [webView loadHTMLString:NSLocalizedString(@" ", nil) baseURL:nil];
    
    hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    hud.delegate = self;
    hud.labelText = NSLocalizedString(@" ", nil);
    //    [hud show:NO];
    
    [self hideToolbar];
    [NSThread detachNewThreadSelector:@selector(start:) toTarget:self withObject:path];
}

- (void) loadBook{
    
    [currentPageLabel setText:@"0/0"];
    
    
    NSString* path=strUpubPath;
    NSLog(@"strUpubPath:%@",strUpubPath);
    currentSpineIndex = 0;
    currentPageInSpineIndex = 0;
    pagesInCurrentSpineCount = 0;
    totalPagesCount = 0;
    searching = NO;
    epubLoaded = NO;
    
    self.isClearWebViewContent = YES;
    [webView loadHTMLString:NSLocalizedString(@" ", nil) baseURL:nil];
    
    hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    hud.delegate = self;
    hud.labelText = NSLocalizedString(@" ", nil);
    
    [self hideToolbar];
    [NSThread detachNewThreadSelector:@selector(start:) toTarget:self withObject:path];
}

-(void)start:(NSString *)path{
    
    self.bookLoader = [[EPubBookLoader alloc] initWithPath:path];
    
    
    if(bookLoader.error == 1){
        pan.enabled = NO;
        [webView loadHTMLString:NSLocalizedString(@"parse_error", nil) baseURL:nil];
//        [DownloadedItem SQPDeleteWhere:[NSString stringWithFormat:@"strSavePath = '%@'",self.strUpubPath]];
        NSFileManager* manager = [NSFileManager defaultManager];
        if([manager fileExistsAtPath:self.strUpubPath]){
            [manager removeItemAtPath:self.strUpubPath error:nil];
        }
    }else{
        epubLoaded = YES;
        
        NSMutableArray *items = [FileHelper getDataFromFile:@"history"];
        if(items.count < 100){
            NSArray *array = [path componentsSeparatedByString:@"/"];
            
            for(NSDictionary *item in items){
                if([[item objectForKey:@"name"] isEqualToString:[array objectAtIndex:(array.count-1)]]){
                    [FileHelper deleteData:item ofFile:@"history"];
                }
            }
            NSMutableDictionary *book = [[NSMutableDictionary alloc] init];
            [book setObject:[array objectAtIndex:(array.count-1)] forKey:@"name"];
            [book setObject:path forKey:@"path"];
            
            [FileHelper prependData:book toFile:@"history"];
            
        }
        
        [self toLastReadPage];
        if(currentSpineIndex > bookLoader.spineArray.count-1){
            currentSpineIndex = 0;
        }
        [self performSelectorOnMainThread:@selector(updatePagination) withObject:nil waitUntilDone:NO];
        
    }
}


- (void) chapterDidFinishLoad:(Chapter *)chapter{
    totalPagesCount+=chapter.pageCount;
    
    
    if(chapter.chapterIndex + 1 < [bookLoader.spineArray count]){
        
        [[bookLoader.spineArray objectAtIndex:chapter.chapterIndex+1] setDelegate:self];
        [[bookLoader.spineArray objectAtIndex:chapter.chapterIndex+1] loadChapterWithWindowSize:webView.bounds fontPercentSize:currentTextSize];
        [currentPageLabel setText:[NSString stringWithFormat:@"0/%d", totalPagesCount]];
    } else {
        [currentPageLabel setText:[NSString stringWithFormat:@"%d/%d",[self getGlobalPageCount], totalPagesCount]];
        [self.pageView.sliderPageView setValue:(float)100*(float)[self getGlobalPageCount]/(float)totalPagesCount animated:YES];
        paginating = NO;
        NSLog(@"Pagination Ended!");
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"bookDidLoaded" object:nil];
    }
}

- (int) getGlobalPageCount{
    int pageCount = 0;
    for(int i=0; i<currentSpineIndex; i++){
        pageCount += [[bookLoader.spineArray objectAtIndex:i] pageCount];
    }
    pageCount+=currentPageInSpineIndex+1;
    return pageCount;
}

- (void) loadSpine:(int)spineIndex atPageIndex:(int)pageIndex {
    @try {
        
        NSURL* epubUrl = [NSURL fileURLWithPath:[[bookLoader.spineArray objectAtIndex:spineIndex] spinePath]];
        hud = [[MBProgressHUD alloc] initWithView:self.view];
        
        [self.view addSubview:hud];
        
        [hud show:NO];
        // 0.5秒后消失
        [hud hide:YES afterDelay:0.5];
        [self hideToolbar];
        [self hiddenLightView];
        [self hideHeaderBar];
        [self hiddenReaderList];
        
        if (!htmlData) {
            htmlData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath: epubUrl.path]];
            NSString* strHtml = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
            
            htmlData=[strHtml dataUsingEncoding:NSUTF8StringEncoding];
            strHtml=nil;
            
        }
        
        self.isClearWebViewContent = NO;
        [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:epubUrl];
        currentPageInSpineIndex = pageIndex;
        currentSpineIndex = spineIndex;
        NSLog(@"00-----------------00");
    }
    @catch (NSException *exception) {
        NSLog(@"WebViewLoadException:%@",exception.reason);
    }
    
}

/**
 *  点击目录打开相应的页面
 *
 *  @param spineIndex 点击的目录的索引
 */

- (void) loadSpine:(int)spineIndex atPageIndex:(int)pageIndex highlightSearchResult:(Reader_listView*)theResult{
    
    webView.hidden = YES;
    
    hud = [[MBProgressHUD alloc] initWithView:self.view];
    
    [self.view addSubview:hud];
    [hud show:NO];
    // 0.5秒后消失
    [hud hide:YES afterDelay:0.5];
    
    [self hideToolbar];
    [self hiddenLightView];
    [self hideHeaderBar];
    [self hiddenReaderList];
    
    NSURL* url = [NSURL fileURLWithPath:[[bookLoader.spineArray objectAtIndex:spineIndex] spinePath]];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    currentPageInSpineIndex = pageIndex;
    currentSpineIndex = spineIndex;
    if(!paginating){
        [currentPageLabel setText:[NSString stringWithFormat:@"%d/%d",[self getGlobalPageCount], totalPagesCount]];
        
    }
}

CGFloat dx;
CGPoint startLocation;

/** 左右滑动手势 **/
- (void)onPangesture:(UIPanGestureRecognizer *)sender {
    [self hideToolbar];
    [self hiddenLightView];
    [self hideHeaderBar];
    [self hiddenReaderList];
    if (sender.state == UIGestureRecognizerStateBegan) {
        
        startLocation = [sender locationInView:webView];
        
    }
    else if (sender.state == UIGestureRecognizerStateChanged){
        CGPoint stopLocation = [sender locationInView:webView];
        
        dx = stopLocation.x - startLocation.x;
        [self gotoPositionOffset:currentPageInSpineIndex*webView.frame.size.width+dx];
        
    }
    else if (sender.state == UIGestureRecognizerStateEnded) {
        
        [self goToPageWithAnim];
    }
    
}
/** 滑动到相应位置 **/
-(void)goToPageWithAnim{
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        NSString* goToOffsetFunc = [NSString stringWithFormat:@" function pageScroll(xOffset){ window.scroll(xOffset,0); } "];
        //下一页
        NSString* goTo = [[NSString alloc]init];
        if (dx>0) {
            if(!paginating){
                if(currentPageInSpineIndex+1<pagesInCurrentSpineCount){
                    currentPageInSpineIndex++;
                    if (currentPageInSpineIndex >= pagesInCurrentSpineCount) {
                        currentPageInSpineIndex = pagesInCurrentSpineCount - 1;
                    }
                    goTo =[NSString stringWithFormat:@"pageScroll(%f)", -currentPageInSpineIndex*webView.frame.size.width];
                    [webView stringByEvaluatingJavaScriptFromString:goToOffsetFunc];
                    [webView stringByEvaluatingJavaScriptFromString:goTo];
                } else {
                    [self gotoNextSpine];
                }
            }
            //         上一页
        }else{
            
            if (!paginating) {
                if(currentPageInSpineIndex-1>=0){
                    currentPageInSpineIndex--;
                    goTo =[NSString stringWithFormat:@"pageScroll(%f)", -currentPageInSpineIndex*webView.frame.size.width];
                    [webView stringByEvaluatingJavaScriptFromString:goToOffsetFunc];
                    [webView stringByEvaluatingJavaScriptFromString:goTo];
                } else {
                    
                    if(!enablePaging){
                        if(currentSpineIndex!=0){
                            int targetPage = [[bookLoader.spineArray objectAtIndex:(currentSpineIndex-1)] pageCount];
                            
                            [self loadSpine:--currentSpineIndex atPageIndex:targetPage-1 highlightSearchResult:nil];
                        }
                    }else{
                        //不分页条件下，上一个章节最后一页，-1标示
                        if(currentSpineIndex-1>=0){
//                            [self loadSpine:--currentSpineIndex atPageIndex:targetPage-1];
                        }
                            
                        //
                    }
                }
            }
            
        }
        
    } completion:^(BOOL finished) {
        [self endAnimationSettinhPageLabel];
        
    }];
}
/** 结束滑动之后 设置文本 **/
-(void)endAnimationSettinhPageLabel{
    if(!enablePaging){
        /**
         *  顶端显示的页数
         */
        
        [currentPageLabel setText:[NSString stringWithFormat:@"%d/%d",[self getGlobalPageCount], totalPagesCount]];
        [self.pageView.sliderPageView setValue:(float)100*(float)(currentPageInSpineIndex+1)/(float)pagesInCurrentSpineCount animated:YES];
    }else{
        if(!paginating){
            [currentPageLabel setText:[NSString stringWithFormat:@"%d/%d",[self getGlobalPageCount], totalPagesCount]];
            [self.pageView.sliderPageView setValue:(float)100*(float)[self getGlobalPageCount]/(float)totalPagesCount animated:YES];
        }
    }
    
    
    
    [self recordLastReadPage];
    
}
/** 偏移到相应位置 **/
-(void) gotoPositionOffset:(CGFloat)offset{
    //    [UIView animateWithDuration:0.001 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    NSString* goToOffsetFunc = [NSString stringWithFormat:@" function pageScroll(xOffset){ window.scroll(xOffset,0); } "];
    NSString* goTo =[NSString stringWithFormat:@"pageScroll(%f)", -offset];
    [webView stringByEvaluatingJavaScriptFromString:goToOffsetFunc];
    [webView stringByEvaluatingJavaScriptFromString:goTo];
    //    } completion:^(BOOL finished) {
    //
    //    }];
    
}

- (void) gotoPageInCurrentSpine:(int)pageIndex{
    webView.hidden = NO;
    //    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    float pageOffset = pageIndex*webView.bounds.size.width;
    NSString* goToOffsetFunc = [NSString stringWithFormat:@" function pageScroll(xOffset){ window.scroll(xOffset,0); } "];
    NSString* goTo =[NSString stringWithFormat:@"pageScroll(%f)", pageOffset*-1];
    [webView stringByEvaluatingJavaScriptFromString:goToOffsetFunc];
    [webView stringByEvaluatingJavaScriptFromString:goTo];
    
    //    } completion:^(BOOL finished) {
    //        [self endAnimationSettinhPageLabel];
    //
    //    }];
    
}



/**
 *  跳转到下一章节
 */
- (void) gotoNextSpine {
    if(!paginating){
        if(currentSpineIndex+1<[bookLoader.spineArray count]){
            [self loadSpine:++currentSpineIndex atPageIndex:0 highlightSearchResult:nil];
        }
    }
}

- (void) gotoPrevSpine {
    if(!paginating){
        if(currentSpineIndex-1>=0){
            [self loadSpine:--currentSpineIndex atPageIndex:0];
        }
    }
}

//目录
-(void)btnReaderList_Clicked:(id)sender{
    
    if (isHiddenReaderList == YES) {
        //    // 创建目录
        NSArray *nibList = [[NSBundle mainBundle] loadNibNamed:@"Reader_listView" owner:nil options:nil];
        self.tblReaderList = [nibList objectAtIndex:0];
        self.tblReaderList.frame =CGRectMake(-PHONE_WIDTH, BACK_HEIGHT, PHONE_WIDTH, self.view.frame.size.height-TOOL_BAR_HEIGHT);
        self.tblReaderList.arrData = bookLoader.spineArray;
        self.tblReaderList.btnTableBack.alpha = 0.0;
        
        [self.view addSubview:tblReaderList];
        
        [self.tblReaderList setGoPageBlock:^(NSInteger row) {
            [self hideToolbar];
            [self hiddenReaderList];
            
            [self loadSpine:(int)row atPageIndex:0 highlightSearchResult:nil];
        }];
        [self.tblReaderList setBtnDissReaderList:^{
            [self hiddenReaderList];
        }];
        
        [self showReaderList];
        
    }else{
        [self hiddenReaderList];
    }
    
}
//收回目录
-(void)btnDissReaderList:(id)sender{
    [self hiddenReaderList];
}
//设施屏幕亮度
-(void)btnLight_Clicked:(id)sender{
    
    
    if (isHiddenLightView == YES) {
        NSArray *nibLight = [[NSBundle mainBundle]loadNibNamed:@"ReaderLightView" owner:nil options:nil];
        self.lightView = [nibLight objectAtIndex:0];
        CGRect frame = self.lightView.frame;
        frame.origin.y = [UIScreen mainScreen].bounds.size.height;
        self.lightView.frame = frame;
        [self.view addSubview:lightView];
        
        [self showLightView];
        [self.lightView.sliderLightView setMinimumValue:0.0];
        [self.lightView.sliderLightView setMaximumValue:1.0];
        
        float value = [UIScreen mainScreen].brightness;
        self.lightView.sliderLightView.value = value;
        [self.lightView.sliderLightMin setText:[NSString stringWithFormat:@"%.f%%",value*100]];
        [self.lightView setSliderBlock:^{
            [UIScreen mainScreen].brightness = self.lightView.sliderLightView.value;
            float v = self.lightView.sliderLightView.value;
            NSLog(@"%.f",v);
            [self.lightView.sliderLightMin setText:[NSString stringWithFormat:@"%.f%%",v*100]];
        }];
        
    }else{
        
        [self hiddenLightView];
        [self hideHeaderBar];
    }
    
}
/**
 *  移除目录
 */
-(void)hiddenReaderList{
    self.tblReaderList.btnTableBack.alpha = 0.0;
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    self.tblReaderList.frame = CGRectMake(-PHONE_WIDTH, BACK_HEIGHT, PHONE_WIDTH, self.view.frame.size.height-TOOL_BAR_HEIGHT);
    
    [UIView commitAnimations];
    isHiddenReaderList = YES;
    [btnList setIconNormal:@"f04e"];

}
/**
 *  显示目录
 */
-(void)showReaderList{
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    self.tblReaderList.frame = CGRectMake(0, BACK_HEIGHT, PHONE_WIDTH, self.view.frame.size.height-TOOL_BAR_HEIGHT);
    
    [UIView commitAnimations];
    self.tblReaderList.btnTableBack.alpha = 0.0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:1.5 animations:^{
            self.tblReaderList.btnTableBack.alpha = 0.7;
        }];
    });
    
    isHiddenReaderList = NO;
    [btnList setIconNormal:@"f02a"];
    
    [tblReaderList.tblReaderList reloadData];
}
/**
 *  移除调试亮度的view
 */
-(void)hiddenLightView{
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    self.lightView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, READER_LIST_TOP_BUTTON);
    [UIView commitAnimations];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.lightView removeFromSuperview];
    });
    isHiddenLightView = YES;
}
/**
 *  显示调试亮度的view
 */
-(void)showLightView{
    CGFloat toolBarHeight = IPHONE6PLUS?READER_LIST_TOP_BUTTON + 12:READER_LIST_TOP_BUTTON;
    CGFloat lightViewY = IPHONE6PLUS?self.view.frame.size.height-toolBarHeight-READER_LIST_TOP_BUTTON:self.view.frame.size.height-READER_LIST_TOP_BUTTON*2;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    self.lightView.frame = CGRectMake(0, lightViewY, self.view.frame.size.width, READER_LIST_TOP_BUTTON);
    [UIView commitAnimations];
    isHiddenLightView = NO;
    
}

-(void)btnJumpPage_Clicked:(id)sender{
    
    [self.view addSubview:self.pageView];
    
    if (currentPageInSpineIndex !=0) {
        [self.pageView.sliderPageMin setText:[NSString stringWithFormat:@"%d", currentPageInSpineIndex+1]];
    }else{
        [self.pageView.sliderPageMin setText:[NSString stringWithFormat:@"%d", currentPageInSpineIndex]];
    }
    [self.pageView.sliderPageMax setText:[NSString stringWithFormat:@"%d", pagesInCurrentSpineCount]];
    CGFloat pageY = self.pageView.frame.origin.y;
    CGFloat selfHeight = self.view.frame.size.height;
    if((int)pageY == (int)selfHeight){
        self.pageView.isLight = NO;
        [self.pageView setSliderBlock:^{
            if(!enablePaging){
                
                [self.pageView.sliderPageMin setText:[NSString stringWithFormat:@"%d",currentPageInSpineIndex+1]];
            }else{
                if(!paginating){
                    [self.pageView.sliderPageMin setText:[NSString stringWithFormat:@"%d",[self getGlobalPageCount]]];
                }
            }
        }];
        
        [self showHeaderBar];
    }else{
        [self hideHeaderBar];
    }
    [self hiddenLightView];
    
}

//放大字体
- (void) btnBigFont_Clicked:(id)sender{
    [self hiddenLightView];
    [self hideHeaderBar];
    if(!paginating){
        if(currentTextSize+25<=200){
            currentTextSize+=25;
            [self updatePagination];
            if(currentTextSize == 200)
            {
                [btnBigFont setEnabled:NO];
            }
            [btnSmallFont setEnabled:YES];
        }
    }
    
}
//缩小字体
- (void) btnSmallFont_Clicked:(id)sender{
    [self hiddenLightView];
    [self hideHeaderBar];
    if(!paginating){
        if(currentTextSize-25>=50){
            currentTextSize-=25;
            [self updatePagination];
            
            if(currentTextSize==50)
            {
                [btnSmallFont setEnabled:NO];
            }
            [btnBigFont setEnabled:YES];
        }
    }
}

//更改阅读模式按钮
- (void) btnReadMode_Clicked:(id)sender{
    [self hiddenLightView];
    [self hideHeaderBar];
    webView.hidden = YES;
    if (!isNightMode) {
        self.view.backgroundColor=[ReaderTools colorWithHexString:@"161616"];
        strBackGroundCSS=@"addCSSRule('body', 'background-color: transparent; color:#787878;')";
        [btnReadMode setIconNormal:@"f077"];
        [btnReadMode setTitleColor:[ReaderTools colorWithHexString:@"25BD74"] forState:UIControlStateNormal];
        [btnReadMode setIconNormal:@"f03c"];
        isNightMode=YES;
        currentPageLabel.textColor = [ReaderTools colorWithHexString:@"#787878"];
        
    }
    else{
        self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"reader_back"]];
        strBackGroundCSS=@"addCSSRule('body', 'background-color: transparent; color:583c1f;')";
        [btnReadMode setIconNormal:@"f077"];
        [btnReadMode setTitleColor:[ReaderTools colorWithHexString:@"25BD74"] forState:UIControlStateNormal];
        [btnReadMode setIconNormal:@"f077"];
        isNightMode=NO;
        currentPageLabel.textColor = [ReaderTools colorWithHexString:@"#583c1f"];
    }
    // 改变状态栏
    [self setNeedsStatusBarAppearanceUpdate];
    [self updatePagination];
}

//返回目录页面或杂志详细页面
-(void)btnReturn_Click:(id)sender{
    [self hiddenLightView];
    [self hideHeaderBar];

    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [self dismissModalViewControllerAnimated:YES];
}
//跳转页码函数
- (void) slidingStarted:(id)sender{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFade;
    [currentPageLabel2.layer addAnimation:transition forKey:nil];
    currentPageLabel2.frame = CGRectMake((self.view.frame.size.width-currentPageLabel2.frame.size.width)/2, currentPageLabel2.frame.origin.y, currentPageLabel2.frame.size.width, currentPageLabel2.frame.size.height);
    
    
    int targetPage = 0;
    NSString *text;
    
    if(enablePaging){
        targetPage = ((self.pageView.sliderPageView.value/(float)100)*(float)totalPagesCount);
        if (targetPage==0) {
            targetPage++;
        }
        text = [NSString stringWithFormat:@"%d/%d", targetPage, totalPagesCount];
        
    }else{
        targetPage = ((self.pageView.sliderPageView.value/(float)100)*(float)pagesInCurrentSpineCount);
        if (targetPage==0) {
            targetPage++;
        }
        text = [NSString stringWithFormat:@"%d/%d", targetPage, pagesInCurrentSpineCount];
    }
    // 设置页数
    [currentPageLabel setText:text];
    
}

- (void) slidingChanged:(id)sender{
    int targetPage = 0;
    int chapterIndex = 0;
    int pageIndex = 0;
    NSString *text;
    
    if(enablePaging){
        targetPage = ((self.pageView.sliderPageView.value/(float)100)*(float)totalPagesCount);
        if (targetPage==0) {
            targetPage++;
        }
        
        text = [NSString stringWithFormat:@"%d/%d", targetPage, totalPagesCount];
        
        int pageSum = 0;
        for(chapterIndex=0; chapterIndex<[bookLoader.spineArray count]; chapterIndex++){
            pageSum+=[[bookLoader.spineArray objectAtIndex:chapterIndex] pageCount];
            if(pageSum>=targetPage){
                pageIndex = [[bookLoader.spineArray objectAtIndex:chapterIndex] pageCount] - 1 - pageSum + targetPage;
                break;
            }
        }
        
    }else{
        targetPage = ((self.pageView.sliderPageView.value/(float)100)*(float)pagesInCurrentSpineCount);
        if (targetPage==0) {
            targetPage++;
        }
        text = [NSString stringWithFormat:@"%d/%d", targetPage, pagesInCurrentSpineCount];
        
        pageIndex = targetPage-1;
    }
    
    currentPageInSpineIndex = pageIndex;
    currentPageLabel.text = text;
    currentPageLabel2.text = text;

    
    CGFloat offset = currentPageInSpineIndex*webView.bounds.size.width;
    
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        NSString* goToOffsetFunc = [NSString stringWithFormat:@" function pageScroll(xOffset){ window.scroll(xOffset,0); } "];
        NSString* goTo =[NSString stringWithFormat:@"pageScroll(%f)", -offset];
        [webView stringByEvaluatingJavaScriptFromString:goToOffsetFunc];
        [webView stringByEvaluatingJavaScriptFromString:goTo];
        
    } completion:^(BOOL finished) {
        
        
    }];
    
    
    
}

- (void) slidingEnded:(id)sender{
    int targetPage = 0;
    int chapterIndex = 0;
    int pageIndex = 0;
    NSString *text;
    
    if(enablePaging){
        targetPage = ((self.pageView.sliderPageView.value/(float)100)*(float)totalPagesCount);
        if (targetPage==0) {
            targetPage++;
        }
        
        text = [NSString stringWithFormat:@"%d/%d", targetPage, totalPagesCount];
        
        int pageSum = 0;
        for(chapterIndex=0; chapterIndex<[bookLoader.spineArray count]; chapterIndex++){
            pageSum+=[[bookLoader.spineArray objectAtIndex:chapterIndex] pageCount];
            if(pageSum>=targetPage){
                pageIndex = [[bookLoader.spineArray objectAtIndex:chapterIndex] pageCount] - 1 - pageSum + targetPage;
                break;
            }
        }
        
    }else{
        targetPage = ((self.pageView.sliderPageView.value/(float)100)*(float)pagesInCurrentSpineCount);
        if (targetPage==0) {
            targetPage++;
        }
        text = [NSString stringWithFormat:@"%d/%d", targetPage, pagesInCurrentSpineCount];
        
        pageIndex = targetPage-1;
    }
    
    currentPageInSpineIndex = pageIndex;
    currentPageLabel.text = text;
    currentPageLabel2.text = text;
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.5f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionReveal;
    transition.subtype = kCATransitionFade;
    [currentPageLabel2.layer addAnimation:transition forKey:nil];
    currentPageLabel2.frame = CGRectMake(self.view.frame.size.width, currentPageLabel2.frame.origin.y, currentPageLabel2.frame.size.width, currentPageLabel2.frame.size.height);

    [self hideToolbar];
}



#pragma UIWebView Delegates
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"url: %@", request.URL);
    return YES;
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)theWebView{
    @try {
        NSLog(@"webViewDidFinishLoad");
        if(self.isClearWebViewContent)
            return;
        
        NSString *insertRule1 = [NSString stringWithFormat:@"addCSSRule('html', 'font-size:14px; font-family:ALKATIP Basma Tom; margin:0px;padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;direction:rtl;')", webView.frame.size.height, webView.frame.size.width];
        NSString *insertRule2 = @"addCSSRule('p', 'text-align: justify;')";
        NSString *insertRule3 = @"addCSSRule('img', 'max-width:80%; max-height:100%;border:none;')";
        NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', 'background:transparent;font-weight:normal;text-align: justify;-webkit-text-size-adjust: %d%%;')", currentTextSize];
        NSString *setHighlightColorRule = @"addCSSRule('highlight', 'background-color: yellow;')";
        
        
        
        
        [webView stringByEvaluatingJavaScriptFromString:SHEET];
        [webView stringByEvaluatingJavaScriptFromString:ADDCSSRULE];
        [webView stringByEvaluatingJavaScriptFromString:insertRule1];
        [webView stringByEvaluatingJavaScriptFromString:insertRule2];
        [webView stringByEvaluatingJavaScriptFromString:insertRule3];
        [webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];
        [webView stringByEvaluatingJavaScriptFromString:setHighlightColorRule];
        [webView stringByEvaluatingJavaScriptFromString:strBackGroundCSS];
        int totalWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollWidth"] intValue];
        pagesInCurrentSpineCount =(int)((float)totalWidth/webView.bounds.size.width);
        NSLog(@"----%d,%d",totalWidth,pagesInCurrentSpineCount);
        if(currentPageInSpineIndex > pagesInCurrentSpineCount-1)
            currentPageInSpineIndex = pagesInCurrentSpineCount -1;
        [self gotoPageInCurrentSpine:currentPageInSpineIndex];
    }
    @catch (NSException *exception) {
        NSLog(@"webViewDidFinishLoadexception:%@",exception.reason);
    }
    
}


- (void) updatePagination{
    if(epubLoaded){
        if(!paginating){
            NSLog(@"Pagination Started!");
            [currentPageLabel setText:@"0/0"];
            
            if(!enablePaging){
                totalPagesCount=0;
                paginating = YES;
                hud = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:hud];
                hud.delegate = self;
                hud.labelText = NSLocalizedString(@"", nil);
                //                [hud show:YES];
                [[bookLoader.spineArray objectAtIndex:0] setDelegate:self];
                [[bookLoader.spineArray objectAtIndex:0] loadChapterWithWindowSize:webView.bounds fontPercentSize:currentTextSize];
            }
            [webView loadHTMLString:@"" baseURL:nil];
            
            [self loadSpine:currentSpineIndex atPageIndex:currentPageInSpineIndex];
            
            NSLog(@"pages:%d",currentSpineIndex);
        }
    }
}

-(void)toLastReadPage{
    NSMutableDictionary *last = (NSMutableDictionary *)[ResourceHelper getUserDefaults:self.bookLoader.filePath];
    if(last!=nil){
        currentSpineIndex       = [[last objectForKey:@"currentSpineIndex"] intValue];
        currentTextSize         = [[last objectForKey:@"currentTextSize"] intValue];
        currentPageInSpineIndex = [[last objectForKey:@"currentPageInSpineIndex"] intValue];
    }
}

-(void)recordLastReadPage{
    NSMutableDictionary *last = [[NSMutableDictionary alloc] init];
    NSString *rCurrentSpineIndex = [[NSString alloc] initWithFormat:@"%d",currentSpineIndex];
    NSString *rCurrentPageInSpineIndex = [[NSString alloc] initWithFormat:@"%d",currentPageInSpineIndex];
    NSString *rCurrentTextSize = [[NSString alloc] initWithFormat:@"%d",currentTextSize];
    
    [last setObject:rCurrentSpineIndex forKey:@"currentSpineIndex"];
    [last setObject:rCurrentPageInSpineIndex forKey:@"currentPageInSpineIndex"];
    [last setObject:rCurrentTextSize forKey:@"currentTextSize"];
    
    
    [ResourceHelper setUserDefaults:last forKey:self.bookLoader.filePath];
    
    
}



#pragma mark -
#pragma mark View lifecycle

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

-(void)handleSingleFingerEvent{
    if(self.toolbar.frame.origin.y == self.view.frame.size.height){
        [self showToolbar];
    }else{
        [self hideToolbar];
        [self hiddenLightView];
        [self hideHeaderBar];
        [self hiddenReaderList];
    }
}

-(void)showToolbar{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    
    CGFloat toolBarHeight = IPHONE6PLUS?READER_LIST_TOP_BUTTON + 12:READER_LIST_TOP_BUTTON;
    CGFloat toolBarY = IPHONE6PLUS?self.view.frame.size.height-toolBarHeight:self.view.frame.size.height-READER_LIST_TOP_BUTTON;
    CGFloat backbarHeight = IPHONE6PLUS?BACK_HEIGHT + 12:BACK_HEIGHT;
    
    self.toolbar.frame = CGRectMake(0, toolBarY, self.view.frame.size.width, toolBarHeight);
    self.backbar.frame = CGRectMake(0, 0, self.view.frame.size.width, backbarHeight);
    [self.backbar bringSubviewToFront:self.view.superview];
    
    [UIView commitAnimations];
    // 改变状态栏颜色
    // 通知改变状态栏
    [UIView animateWithDuration:0.3 animations:^{
        [self setNeedsStatusBarAppearanceUpdate];
    }];
    
    
}

-(void)showHeaderBar{
    
    CGFloat toolBarHeight = IPHONE6PLUS?READER_LIST_TOP_BUTTON + 12:READER_LIST_TOP_BUTTON;
    CGFloat lightViewY = IPHONE6PLUS?self.view.frame.size.height-toolBarHeight-READER_LIST_TOP_BUTTON:self.view.frame.size.height-READER_LIST_TOP_BUTTON*2;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    
    self.pageView.frame =  CGRectMake(0, lightViewY, self.view.frame.size.width, READER_LIST_TOP_BUTTON);
    [UIView commitAnimations];
    isHiddenPageView = NO;
    
}

-(void)hideToolbar{
    
    CGFloat toolBarHeight = IPHONE6PLUS?READER_LIST_TOP_BUTTON + 12:READER_LIST_TOP_BUTTON;
    CGFloat backbarHeight = IPHONE6PLUS?BACK_HEIGHT + 12:BACK_HEIGHT;
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    self.toolbar.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, toolBarHeight);
    self.backbar.frame = CGRectMake(0, -backbarHeight, self.view.frame.size.width, backbarHeight);
    self.pageView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, READER_LIST_TOP_BUTTON);
    
    [UIView commitAnimations];
    // 改变状态栏颜色
    // 通知改变状态栏
    [UIView animateWithDuration:0.3 animations:^{
        [self setNeedsStatusBarAppearanceUpdate];
    }];
    
    
}

-(void)hideHeaderBar{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.5];
    isHiddenPageView = YES;
    self.pageView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, READER_LIST_TOP_BUTTON);
    [UIView commitAnimations];
}



-(void)bookDidLoaded:(NSNotification *)notification{
    [hud hide:YES];
}

- (void)viewDidUnload {
    self.toolbar = nil;
    self.webView = nil;
    self.btnLight = nil;
    self.btnSmallFont = nil;
    self.btnBigFont = nil;
    self.pageView.sliderPageView = nil;
    self.currentPageLabel = nil;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    self.toolbar = nil;
    self.webView = nil;
    self.btnLight = nil;
    self.btnSmallFont = nil;
    self.btnBigFont = nil;
    self.self.pageView.sliderPageView = nil;
    self.currentPageLabel = nil;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(BOOL)shouldAutorotate
{
    
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return NO;
    
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}


@end
